package com.cosytek.farmmanager;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link LoginFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class LoginFragment extends Fragment implements View.OnClickListener, ServerRequest.IServerRequestListener {
    private String mAccount;
    private String mPassword;
    private boolean mAutoLogin;

    private OnFragmentInteractionListener mListener;
    private Activity mParent;

    public static final String LOGIN_DATA_CATALOG = "LOGIN";
    public static final String KEY_AUTO_LOGIN = "AutoLogin";
    public static final String KEY_ACCOUNT = "Account";
    public static final String KEY_PASSWORD = "Password";
    public static final String PATH_LOGIN = "/login";

    private View mLoginForm;
    private View mProgressForm;
    private EditText mAccountView;
    private EditText mPasswordView;
    private CheckBox mAutoLoginView;
    private ServerRequest mRequest;

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment LoginFragment.
     */
    public static LoginFragment newInstance(Activity context) {
        LoginFragment fragment = new LoginFragment();

        fragment.loadLoginData(context);
        return fragment;
    }

    public LoginFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    private void loadLoginData(Activity context) {
        SharedPreferences share = context.getSharedPreferences(LOGIN_DATA_CATALOG, Context.MODE_PRIVATE);
        mAccount = share.getString(KEY_ACCOUNT, "");
        mPassword = share.getString(KEY_PASSWORD, "");
        mAutoLogin = share.getBoolean(KEY_AUTO_LOGIN, false);
    }

    private void saveLoginData() {
        if (mParent == null) {
            return;
        }

        SharedPreferences share = mParent.getSharedPreferences(LOGIN_DATA_CATALOG, Context.MODE_PRIVATE);
        SharedPreferences.Editor edit = share.edit();
        edit.putString(KEY_ACCOUNT, mAccount);
        edit.putString(KEY_PASSWORD, mPassword);
        edit.putBoolean(KEY_AUTO_LOGIN, mAutoLogin);

        edit.commit();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View v = inflater.inflate(R.layout.fragment_login, container, false);

        mLoginForm = v.findViewById(R.id.frag_login_login_form);
        mProgressForm = v.findViewById(R.id.common_progress_form);
        mAccountView = (EditText)v.findViewById(R.id.frag_login_account);
        mPasswordView = (EditText)v.findViewById(R.id.frag_login_password);
        mAutoLoginView = (CheckBox)v.findViewById(R.id.frag_login_chb_auto_login);

        Button btnLogin = (Button)v.findViewById(R.id.frag_login_btn_login);
        btnLogin.setOnClickListener(this);

        mAccountView.setText(mAccount);
        mPasswordView.setText(mPassword);
        mAutoLoginView.setChecked(mAutoLogin);

        if (!mAutoLogin || TextUtils.isEmpty(mAccount) || TextUtils.isEmpty(mPassword)) {
            mLoginForm.setVisibility(View.VISIBLE);
        } else {
            attemptLogin();
        }

        return v;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        try {
            mParent = activity;
            mListener = (OnFragmentInteractionListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
        mParent = null;
    }

    @Override
    public void onClick(View v) {
        int vId = v.getId();
        switch (vId) {
            case R.id.frag_login_btn_login:
                attemptLogin();
                break;
        }
    }

    private void attemptLogin() {
        boolean verifyOK = false;
        mLoginForm.setVisibility(View.GONE);

        try {
            mAutoLogin = mAutoLoginView.isChecked();

            mAccount = mAccountView.getText().toString();
            if (TextUtils.isEmpty(mAccount)) {
                mAccountView.setError(mParent.getString(R.string.ERR_ACCOUNT_NEED));
                mAccountView.requestFocus();
                return;
            }

            mPassword = mPasswordView.getText().toString();
            if (TextUtils.isEmpty(mPassword)) {
                mPasswordView.setError(mParent.getString(R.string.ERR_PASSWORD_NEED));
                mPasswordView.requestFocus();
                return;
            }

            mProgressForm.setVisibility(View.VISIBLE);
            mRequest = ServerRequest.newAuthorizeRequest(this, PATH_LOGIN, mAccount, mPassword);
            mRequest.execute();

            verifyOK = true;
        } finally {
            if (!verifyOK) {
                mProgressForm.setVisibility(View.GONE);
                mLoginForm.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public void onRequestCompleted(ServerRequest r, boolean success, ServerError error, String respBody) {
        if (mListener == null) {
            return;
        }

        mProgressForm.setVisibility(View.GONE);
        mLoginForm.setVisibility(View.VISIBLE);

        if (success) {
            saveLoginData();
            Uri.Builder ub = new Uri.Builder();
            mListener.onFragmentInteraction(this, ub.path(PATH_LOGIN).appendQueryParameter("token", respBody).build());
            return;
        }

        if (error != null) {
            switch (error.getCode()) {
                case ServerError.ERR_ACCOUNT_NOT_EXIST:
                    mAccountView.setError(error.getMsg());
                    mAccountView.requestFocus();
                    break;
                case ServerError.ERR_PASSWORD_NOT_MATCH:
                    mPasswordView.setError(error.getMsg());
                    mPasswordView.requestFocus();
                    break;
                default:
                    UIHelper.promptError(mParent, error);
                    break;
            }
        }

    }
}
